package com.hlkj.baojin.utils;

import com.hlkj.baojin.constant.BaojinConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis操作工具
 *
 * @author lzx
 **/
@Component
public class RedisUtils<T> {

    private final Logger logger = LoggerFactory.getLogger(RedisUtils.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate<String, T> redisTemplate;
    private static final long time = 300L;


    /**
     * 保存
     *
     * @param key 键值对的key
     * @param t   键值对的value
     */
    public void setCache(String key, T t) {
        key = convertKey(key);
        try {
            redisTemplate.opsForValue().set(key, t, time, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("缓存添加失败,key: " + key + " value : " + t + " " + e.toString());
        }

    }

    /**
     * 获取
     */
    public T getCache(String key) {
        key = convertKey(key);
        try {
            if (redisTemplate.hasKey(key)) {
                return redisTemplate.opsForValue().get(key);
            }
        } catch (Exception e) {
            logger.error("缓存读取失败,key : " + key + " " + e.toString());
        }
        return null;
    }

    /**
     * 删除
     *
     * @param key
     */
    public void deleteCache(String key) {
        key = convertKey(key);
        try {
            if (redisTemplate.hasKey(key)) {
                redisTemplate.delete(key);
            }
        } catch (Exception e) {
            logger.error("缓存删除失败,key : " + key + " " + e.toString());
        }
    }

    private String convertKey(String key) {
        return BaojinConstant.REDIS_KEY + key;
    }
}
